package com.yy.wga.mp.module.income.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yy.wga.mp.module.income.common.constants.RedisConstant;
import com.yy.wga.mp.module.income.entity.pojo.IncomeUserBalanceDO;
import com.yy.wga.mp.module.income.entity.pojo.IncomeWithdrawRecordDO;
import com.yy.wga.mp.module.income.service.IncomeUserBalanceService;
import com.yy.wga.mp.module.income.service.IncomeWithdrawRecordService;
import com.yy.wga.mp.module.pay.event.TransferCallbackEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: gc
 * @Date: 2024/11/30
 * @Description:
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class IncomeTransferEventListener {

    private final IncomeUserBalanceService userBalanceService;
    private final RedissonClient redissonClient;
    private final IncomeWithdrawRecordService withdrawRecordService;

    @EventListener
    @Transactional
    public void onApplicationEvent(TransferCallbackEvent event) {
        IncomeWithdrawRecordDO withdrawRecord = withdrawRecordService.getOne(new LambdaQueryWrapper<IncomeWithdrawRecordDO>()
                .eq(IncomeWithdrawRecordDO::getAppKey, event.getAppKey())
                .eq(IncomeWithdrawRecordDO::getOrderNo, event.getOutBatchNo()));
        if (withdrawRecord == null) {
            log.error("提现回调未查询到订单信息:{}", JSON.toJSONString(event));
            return;
        }

        // 修改提现记录
        IncomeWithdrawRecordDO update = new IncomeWithdrawRecordDO();
        update.setId(withdrawRecord.getId());
        // 状态 0.申请提现 1.提现拒绝 2.提现中 3.提现失败 4.提现成功
        if ("FINISHED".equals(event.getBatchStatus())) {
            update.setStatus(4);
        } else if ("CLOSED".equals(event.getBatchStatus())) {
            update.setStatus(3);
        } else {
            log.error("提现回调返回未知状态:{}", JSON.toJSON(event));
            return;
        }
        withdrawRecordService.updateById(update);

        // 修改用户余额
        String userBalanceKey = RedisConstant.USER_BALANCE_KEY + withdrawRecord.getUserId();
        RLock lock = redissonClient.getLock(userBalanceKey);
        lock.lock();
        try {
            IncomeUserBalanceDO userBalanceDO = userBalanceService.getOne(new LambdaQueryWrapper<IncomeUserBalanceDO>()
                    .eq(IncomeUserBalanceDO::getAppKey, event.getAppKey())
                    .eq(IncomeUserBalanceDO::getUserId, withdrawRecord.getUserId()));
            if (userBalanceDO == null) {
                log.error("提现回调未查询到用户收益: {}", withdrawRecord.getUserId());
                return;
            }

            IncomeUserBalanceDO updateBalance = new IncomeUserBalanceDO();
            updateBalance.setId(userBalanceDO.getId());
            updateBalance.setInWithdraw(userBalanceDO.getInWithdraw() - withdrawRecord.getAmount());
            if ("FINISHED".equals(event.getBatchStatus())) {
                updateBalance.setWithdraw(userBalanceDO.getWithdraw() + withdrawRecord.getAmount());
            } else {
                updateBalance.setSettle(userBalanceDO.getSettle() + withdrawRecord.getAmount());
            }
            updateBalance.setWithdraw(userBalanceDO.getWithdraw() + withdrawRecord.getAmount());
            userBalanceService.updateById(updateBalance);
        } finally {
            lock.unlock();
        }
    }
}
